package com.study.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

public class SqlSessionUtils {
    private static SqlSessionFactory factory;
    private static ThreadLocal<SqlSession> local =new ThreadLocal<SqlSession>();
    static{
        try {
            factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = local.get();
        if (sqlSession == null) {
             sqlSession = factory.openSession();
            local.set(sqlSession);
        }
        return sqlSession;
    }
    public static void close(){
        SqlSession sqlsession=local.get();
        if(sqlsession != null){
            sqlsession.close();
            local.remove();
        }
    }
}
